//
//  InfoViewController.m
//  MapKitTutorial
//
//  Created by Luca Di Franco on 20/04/10.
//  Copyright 2010 Luca Di Franco. All rights reserved.
//

#import "InfoViewController.h"


@implementation InfoViewController

#pragma mark -
#pragma mark Initialization

- (id)initWithUserLocation:(CLLocation *)userLocation annotation:(id <MKAnnotation>)annotation {
	self = [super init];
	self.title = annotation.title;
	// Creo l'oggetto CLLocation relativo alle coordinate della annotation e calcola la distanza dalla posizione dell'utente
	CLLocation *location = [[CLLocation alloc] initWithLatitude:annotation.coordinate.latitude longitude:annotation.coordinate.longitude];
	distance = [userLocation getDistanceFrom:location];
	// Inizializza il geocoder
	reverseGeocoder = [[MKReverseGeocoder alloc] initWithCoordinate:annotation.coordinate];
	reverseGeocoder.delegate = self;
	return self;
}

#pragma mark -
#pragma mark View life cycle

- (void)loadView {
	[super loadView];
	UILabel *distanceLabel = [[[UILabel alloc] initWithFrame:CGRectMake(5, 0, 310, 24)] autorelease];
	distanceLabel.text = [NSString stringWithFormat:@"Distanza in metri: %.0f", distance];;
	[self.view addSubview:distanceLabel];
}

- (void)viewDidLoad {
	// Avviamo il reverse geocoding
	[reverseGeocoder start];
}

#pragma mark -
#pragma mark MKReverseGeocoderDelegate methods

// Questo metodo viene chiamato quando il reverse geocoding termina con successo
- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFindPlacemark:(MKPlacemark *)placemark {
	NSDictionary *addressData = placemark.addressDictionary;
	// Visualizzo le informazioni contenute del dizionario relativo all'indirizzo
	CGFloat y = 50;
	for (NSString *key in [addressData allKeys]) {
		if ([key compare:@"FormattedAddressLines"] != NSOrderedSame) {
			UILabel *newRow = [[[UILabel alloc] initWithFrame:CGRectMake(5, y, 310, 24)] autorelease];
			newRow.text = [NSString stringWithFormat:@"%@: %@", key, [addressData objectForKey:key]];
			[self.view addSubview:newRow];
			y += 24;
		}
	}
}

// Questo metodo viene chiamato quando il reverse geocoding fallisce
- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFailWithError:(NSError *)error {
	UILabel *geocoderFail = [[[UILabel alloc] initWithFrame:CGRectMake(5, 50, 310, 24)] autorelease];
	geocoderFail.text = @"Reverse geocoding fallito";
	[self.view addSubview:geocoderFail];
}

#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)dealloc {
	[reverseGeocoder release], reverseGeocoder = nil;
    [super dealloc];
}

@end
